package cn.sfrog.project.biz.applet.config;

import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import javax.net.ssl.HttpsURLConnection;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.security.PrivateKey;
import java.security.Signature;
import java.util.Base64;

/**
 * @Author chenl
 * @Date 2024-01-04 11:31
 * @title PayUtil
 * @description
 **/
public class PayUtil {
    @Autowired
    WxPayConfig wxPayConfig;

    @Value("${spring.profiles.active}")
    private String springProfilesActive;
    /**
     * 作用：使用字段appId、timeStamp、nonceStr、package计算得出的签名值
     * 场景：根据微信统一下单接口返回的 prepay_id 生成调启支付所需的签名值
     * @param appId
     * @param timestamp
     * @param nonceStr
     * @param pack package
     * @return
     * @throws Exception
     */
    public String getSign(String appId, long timestamp, String nonceStr, String pack) throws Exception{
        String message = buildMessage(appId, timestamp, nonceStr, pack);
        String paySign= sign(message.getBytes("utf-8"));
        return paySign;
    }

    private String buildMessage(String appId, long timestamp, String nonceStr, String pack) {
        return appId + "\n"
                + timestamp + "\n"
                + nonceStr + "\n"
                + pack + "\n";
    }
    private String sign(byte[] message) throws Exception {
        Signature sign = Signature.getInstance("SHA256withRSA");
        //这里需要一个PrivateKey类型的参数，就是商户的私钥。
        //获取商户私钥
        URL url= new URL("https://pyw.peiyiyiliao.com/wxpay/apiclient_key.pem");
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        InputStream inputStream = conn.getInputStream();
        PrivateKey privateKey = PemUtil.loadPrivateKey(inputStream);
//        if(springProfilesActive.equals("prod")){
//            PrivateKey privateKey = PemUtil.loadPrivateKey(new FileInputStream("/home/peiyiwang/wxpay/apiclient_key.pem"));;
//            // linux 系统
//        }
//        PrivateKey privateKey = PemUtil.loadPrivateKey(new FileInputStream("apiclient_key.pem"));
        sign.initSign(privateKey);
        sign.update(message);
        return Base64.getEncoder().encodeToString(sign.sign());
    }

}
